//
//  PopoverPresentationController.swift
//  DSWeiBo
//
//  Created by Frank Wang on 7/7/16.
//  Copyright © 2016 Frank Wang. All rights reserved.
//

import UIKit

@available(iOS 8.0 ,*)

class PopoverPresentationController: UIPresentationController {
        
        /// 定义属性保存菜单大小。
        var presentFrame = CGRectZero
        
        
        
        /**
         初始化方法，用于创建负责专场动画的对象
         
         - parameter presentedViewController:  被展现的控制器
         - parameter presentingViewController: 发起的控制器 xcode 6 是nil，Xcode7 是也指针
         
         - returns: 负责专场动画的对象
         */
      override  init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
                
                super.init(presentedViewController: presentedViewController, presentingViewController: presentedViewController)
                
        }
        
        
//        即将布局转场子视图时调用
        override func containerViewWillLayoutSubviews() {
//                containerView //容器视图
//                presentedView() //展现视图
                
                if presentFrame == CGRectZero {
                        presentedView()?.frame = CGRectMake(100, 56, 200, 200)
                }else{
                        presentedView()?.frame = presentFrame
                }
                
                
                //在容器视图上添加一个蒙板，插入到原视图的下面，因为展现视图和蒙板都在一个视图上，而后添加的会盖住先添加的
             
                containerView?.insertSubview(coverView, atIndex: 0)
        }
        
        //MARK－懒加载
        private lazy var coverView : UIView = {
                let view = UIView()
                view.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
                view.frame = UIScreen.mainScreen().bounds
                
                let tap = UITapGestureRecognizer(target: self, action: #selector(PopoverPresentationController.close))
                view.addGestureRecognizer(tap)
                return view
        }()
        
        func close() {
                //拿到当前弹出的控制器
                presentedViewController.dismissViewControllerAnimated(true, completion: nil)
        }
}
